﻿using System;
using System.Data;
using System.Linq;
using Solution.BusinessObject;
using Solution.CMS.MainDSTableAdapters;
using Solution.Core;
using Solution.Utilities;

namespace Solution.CMS
{
    public partial class Albums : PageBase
    {
        readonly MainDS _mainDs = new MainDS();
        private MainDS.ContentsRow _contentsRow;
        private ContentsTableAdapter _contentsTableAdapter;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Request["act"] != null)
                {
                    var id = 0;

                    this.Action = Request["act"].ConvertToEnum<PageAction>();

                    if (Request["id"] != null)
                    {
                        id = Convert.ToInt32(Request["Id"]);
                    }

                    if (id == 0)
                    {
                        return;
                    }

                    if (Action == PageAction.Delete)
                    {
                        _contentsTableAdapter = new ContentsTableAdapter
                                                    {
                                                        Connection = CommonBO.SqlConnection
                                                    };
                        _contentsTableAdapter.Connection.Open();

                        _contentsTableAdapter.Fill(_mainDs.Contents);
                        _contentsRow = _mainDs.Contents.FindById(id);
                        if (_contentsRow != null)
                        {
                            // get detail rows
                            var detailContentsTableAdapter = new DetailContentsTableAdapter
                            {
                                Connection = CommonBO.SqlConnection
                            };
                            detailContentsTableAdapter.Fill(_mainDs.DetailContents);
                            var detailContentsRows = _mainDs.DetailContents.Where(t => t.Content_Id == _contentsRow.Id).ToArray();
                            foreach (var detailContentsRow in detailContentsRows)
                            {
                                detailContentsRow.Delete();
                            }
                            detailContentsTableAdapter.Update(_mainDs.DetailContents);
                            _contentsRow.Delete();
                        }
                        _contentsTableAdapter.Update(_mainDs.Contents);
                    }

                    _contentsTableAdapter.Connection.Close();
                }
                var contents = CommonBO.MasterEDM.Contents.ToList();
                grdAlbums.DataSource = contents;
                grdAlbums.DataBind();
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
    }
}